import {AfterViewInit, Component, OnInit} from '@angular/core';
import {AppContextService} from "../../service/app-context.service";
import {UploadService} from "../../service/upload.service";
import {NzMessageService} from "ng-zorro-antd/message";
import {NzModalService} from "ng-zorro-antd/modal";
import {PathService} from "../../service/path.service";
import {SingleUploadTask, UploadTask} from "../../model/upload-task";
import {FileViewService} from "../../service/file-view.service";
import {UploadFileErrorReporter} from "../../model/upload-dto";

@Component({
  selector: 'app-upload',
  templateUrl: './upload.component.html',
  styleUrls: ['./upload.component.less']
})
export class UploadComponent implements OnInit, AfterViewInit {

  dirInput: HTMLInputElement | undefined
  fileInput: HTMLInputElement | undefined

  uploadModalVisible = false

  tableLayout = {
    y: '400px'
  }

  task: UploadTask = UploadComponent.fakeTask()

  constructor(
    private ctx: AppContextService,
    private uploadService: UploadService,
    private message: NzMessageService,
    private pathService: PathService,
    public fileViewService: FileViewService,
    private modalService: NzModalService
  ) {
  }

  ngOnInit(): void {
  }

  ngAfterViewInit(): void {
    const ref = this
    this.fileInput = UploadComponent.findFileInput("uploader-file")
    this.dirInput = UploadComponent.findFileInput("uploader-dir")

    ref.ctx.doSelectUploadFiles.subscribe({
      next(flag) {
        ref.tryDoUpload(flag)
      }
    })
  }

  tryDoUpload(isFile: boolean) {
    this.uploadService.checkUploadPerm(() => {
      if (isFile) {
        // @ts-ignore
        this.fileInput?.value = null
        this.fileInput?.click()
      } else {
        this.message.error('暂时不支持上传文件夹')
      }
    })
  }

  uploadFileEvent() {
    const files: FileList | null | undefined = this.fileInput?.files
    if (files !== undefined && files !== null && files.length > 0)
      this.uploadFile(files)
  }

  uploadDirEvent() {
    const files: FileList | null | undefined = this.dirInput?.files
    console.log('上传目录' + files)
    if (files !== undefined && files !== null && files.length > 0)
      this.uploadDir(files)
  }

  uploadFile(list: FileList) {
    this.uploadModalVisible = true
    this.task = this.uploadService.registerUploadTask(this.pathService.getFileUrl(), list)
    this.uploadService.onMainTaskStateChange(this.task)
    this.uploadService.onMainTaskStateChange(this.task)
  }

  uploadDir(list: FileList) {
    console.log('上传目录: 还没有实现的功能')
  }

  onTaskChange() {
    this.uploadService.onMainTaskStateChange(this.task)
  }

  onSubTaskChange(single: SingleUploadTask) {
    this.uploadService.onSubTaskStateChange(single)
  }

  closeModal() {
    this.uploadService.addHistoryTask(this.task)
    this.uploadModalVisible = false
  }

  toggleSingleTaskDeleteBtnVisible(single: SingleUploadTask) {
    single.deleteBtnVisible = !single.deleteBtnVisible
  }

  singleTaskShowDeleteBtn(single: SingleUploadTask) {
    single.deleteBtnVisible = true
  }

  singleTaskInvisibleDeleteBtn(single: SingleUploadTask) {
    single.deleteBtnVisible = false
  }

  urlDecode(path: string): string {
    const decoded = decodeURIComponent(path)
    if (decoded.length == 0) {
      return '/'
    } else {
      if (decoded.charAt(0) != '/')
        return '/' + decoded
      else
        return decoded
    }
  }

  private static findFileInput(key: string): HTMLInputElement {
    const el = document.getElementById(key)
    if (el == null) {
      throw "未找到上传文件的元素"
    } else {
      return el as HTMLInputElement
    }
  }

  private static fakeTask(): UploadTask {
    return {
      contentLoading: false,
      title: '开始上传',
      tag: '上传中',
      tagColor: 'blue',
      tagIcon: '',
      btnDisable: false,
      btnLoading: false,
      taskId: '',
      state: 3,
      success: true,
      percent: 88,
      progressAutoCheckerId: -1,
      errorMsg: null,
      uploadPath: '/电影/test-0/s/路径测试',
      subTasks: [],
      error: null,
      nativeFiles: [],
      totalSize: 11231212,
      availableCount: 0
    }
  }

  private static fakeError(): UploadFileErrorReporter {
    return {
      uploadPath: '',
      endpoint: '/static/电影/abc',
      limit: 121212,
      free: 212121212
    }
  }
}
